package com.cloudcc.mobile.dao;

import java.io.File;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.util.FileUtil;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

public class DownLoadCamCardDao {
	private static String name;
	private Notification notification;
	private NotificationManager manager;
	private DefaultHttpClient httpClient;
	private int len;
	private static String path = Tools.getImagePath("/CloudCC/FuJian/");

	public void downLoadCamcard(String url, final Context context) {
		// http://static0.intsig.net/r/output/CamCard_Lite_OpenApi.apk
		name = url.substring(Tools.getCharacterPosition(url, "/", 5) + 1,
				url.length());
		notifacation(context);
		String fileName = path + "/" + name;
		File file = new File(fileName);
		if (file.exists()) {
			FileUtil.deleteFile(file);
		}
		HttpUtils http = new HttpUtils();
		httpClient = (DefaultHttpClient) http.getHttpClient();
		httpClient.addRequestInterceptor(null);
		if (path == null) {
			Tools.showInfo(context, "没有sd卡，或者内存不足！");
			return;
		}
		HttpHandler httpHandler = http.download(url, path + "/" + name, true,// 如果目标文件存在，接着未完成的部分继续下载
				false,// 如果从请求返回信息中获取到文件名，下载完成后自动重命名
				new RequestCallBack<File>() {
					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						NotificationUtils.clearNotification(context, 101);
						installApk(new File(path + "/" + name), context);
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						NotificationUtils.clearNotification(context, 101);
						Tools.showInfo(context, "下载失败");
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						super.onLoading(total, current, isUploading);
						Message msg = new Message();
						msg.what = 1000;
						msg.obj = current;
						loadhandler.sendMessage(msg);
						len = (int) (current * 100 / total);
						if (current == total) {
							loadhandler.sendEmptyMessage(2);
						}
					}
				});

	}

	protected void notifacation(Context context) {
		manager = (NotificationManager) context
				.getSystemService(context.NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.icon = R.drawable.chatter_download;
		notification.tickerText = "全能名片王下载......";
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		// 通知栏显示所有布局文件
		notification.contentView = new RemoteViews(context.getPackageName(),
				R.layout.loading_notification);
		notification.contentIntent = null;
		notification.contentView.setTextViewText(R.id.loadingName, "正在下载\n("
				+ name + ")");
		manager.notify(101, notification);
	}

	Handler loadhandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1000) {
				notification.contentView.setTextViewText(
						R.id.content_view_text1, len + "%");
				notification.contentView.setProgressBar(
						R.id.content_view_progress, 100, len, false);
				if (len == 100) {
					notification.contentView.setTextViewText(R.id.loadingName,
							"下载完成(" + name + ")!");
				}
				manager.notify(101, notification);
			}
		};
	};

	protected void installApk(File file, Context context) {
		try {
			Intent i = new Intent();
			i.setAction(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.fromFile(file),
					"application/vnd.android.package-archive");
			context.startActivity(i);
		} catch (Exception e) {
			Tools.showInfo(context, "安装失败");
			Tools.handle(e);
		}
	}
}
